package com.uyayo.portal.controller;

import com.uyayo.cms.entity.*;
import com.uyayo.cms.model.*;
import com.uyayo.cms.service.*;
import com.uyayo.framework.message.model.Result;
import com.uyayo.framework.pagehelper.pojo.PageBean;
import com.uyayo.framework.web.annotation.GetRequestInfo;
import com.uyayo.framework.web.model.RequestDefaultInfo;
import com.uyayo.portal.biz.CmsSiteBiz;
import com.uyayo.portal.biz.ParamBiz;
import com.uyayo.portal.vo.*;
import com.uyayo.portal.wrap.CmsCommentWrap;
import com.uyayo.portal.wrap.CmsReplyWrap;
import com.uyayo.ucenter.entity.Member;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.dozer.DozerBeanMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


/**
 *
 * <p>
 * Description:回复的Controller
 * </p>
 * <p>
 * Company: www.lelekeji.com
 * </p>
 * 
 * @author 乐乐科技.胡逢君
 * @date 2016-4-23下午4:03:35
 * @version 1.0
 */
@Controller
@RequestMapping()
public class CmsReplyController {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	private final ParamBiz paramBiz;

	private final CmsSiteBiz cmsSiteBiz;

	private final CmsSiteService cmsSiteService;

	private final CmsChannelService cmsChannelService;

	private final CmsArticleService cmsArticleService;

	private final CmsCommentService cmsCommentService;

	private final CmsReplyService cmsReplyService;

	private final  CmsArticleLikeService cmsArticleLikeService;

	private final  CmsCommentLikeService cmsCommentLikeService;

	private final  CmsReplyLikeService cmsReplyLikeService;

	private  final MessageSource messageSource;

	private final DozerBeanMapper dozerBeanMapper;

	private final CmsTagService cmsTagService;

	private final CmsArticleCategoryService cmsArticleCategoryService;

	@Autowired
	public CmsReplyController(MessageSource messageSource, CmsArticleService cmsArticleService, CmsChannelService cmsChannelService, CmsSiteService cmsSiteService, CmsSiteBiz cmsSiteBiz, ParamBiz paramBiz, CmsCommentService cmsCommentService, CmsReplyService cmsReplyService, CmsArticleLikeService cmsArticleLikeService, CmsCommentLikeService cmsCommentLikeService, CmsReplyLikeService cmsReplyLikeService, DozerBeanMapper dozerBeanMapper, CmsTagService cmsTagService, CmsArticleCategoryService cmsArticleCategoryService) {
		this.messageSource = messageSource;
		this.cmsArticleService = cmsArticleService;
		this.cmsChannelService = cmsChannelService;
		this.cmsSiteService = cmsSiteService;
		this.cmsSiteBiz = cmsSiteBiz;
		this.paramBiz = paramBiz;
		this.cmsCommentService = cmsCommentService;
		this.cmsReplyService = cmsReplyService;
		this.cmsArticleLikeService = cmsArticleLikeService;
		this.cmsCommentLikeService = cmsCommentLikeService;
		this.cmsReplyLikeService = cmsReplyLikeService;
		this.dozerBeanMapper = dozerBeanMapper;
		this.cmsTagService = cmsTagService;
		this.cmsArticleCategoryService = cmsArticleCategoryService;
	}


	@ResponseBody
	@RequestMapping(method=RequestMethod.POST,value={"/reply"})
	public Result reply(HttpServletRequest request, @Validated CmsReplyVO cmsReplyVO, Errors errors, @GetRequestInfo RequestDefaultInfo requestInfo) {

		try {
			if (errors.hasErrors()) {
				return new Result(400,errors.getFieldError().getDefaultMessage());
			}
			Subject subject = SecurityUtils.getSubject();
			if(!subject.isAuthenticated()){
				String message = messageSource.getMessage("user.login",new Object[]{}, request.getLocale());
				logger.error(message);
				return new Result(5001,message);
			}
			Member member = (Member) subject.getPrincipal();
			CmsReply cmsReply = new CmsReply();
			cmsReply.setCreateTime(new Date());
			cmsReply.setReplyFromMemberId(member.getId());
			cmsReply.setReplyToMemberId(cmsReplyVO.getReplyToMemberId());
			cmsReply.setCommentId(cmsReplyVO.getCommentId());
			cmsReply.setArticleId(cmsReplyVO.getArticleId());
			cmsReply.setIp(requestInfo.getRequestIp());
			cmsReply.setContent(cmsReplyVO.getContent());
			cmsReply.setReplyTargetId(cmsReplyVO.getReplyTargetId());
			cmsReply.setReplyTargetType(cmsReplyVO.getReplyTargetType());
			cmsReply.setStatus((short) 1);
			cmsReplyService.createCmsReply(cmsReply);
			return new Result(200,"回复成功！",request.getHeader("Referer"));
		}catch (Exception e) {
			String message = messageSource.getMessage("server.error.500",new Object[]{}, request.getLocale());
			logger.error(message,e);
			return new Result(400,message);
		}
	}

	@ResponseBody
	@RequestMapping(method=RequestMethod.GET,value={"/reply"})
	public Result findReply(@RequestParam(value = "pageCurrent",required = false, defaultValue = "1") Integer pageCurrent, //第几页
							@RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize,@Validated CmsReplyCondition cmsReplyCondition, Errors errors) {

		try {

			if (errors.hasErrors()) {
				return new Result(400,errors.getFieldError().getDefaultMessage());
			}
			CmsComment cmsComment = new CmsComment();
			cmsComment.setCreateTime(new Date());
			cmsReplyCondition.setStatus((short) 1);
			PageBean<CmsReplyBO> pageBean =cmsReplyService.selectReplyListByPaging(pageCurrent,pageSize,"createTime","desc",cmsReplyCondition);

			Subject subject = SecurityUtils.getSubject();
			List<CmsReplyLike> cmsReplyLikes = new ArrayList<>();
			if(subject.isAuthenticated()){
				Member member = (Member) subject.getPrincipal();
				Example example = new Example(CmsReplyLike.class);
				Example.Criteria criteria = example.createCriteria();
				criteria.andEqualTo("memberId",member.getId());
				List<Long> list = pageBean.getList().stream().map(CmsReply::getId).collect(Collectors.toList());
				if(list.size()>0) {
					criteria.andIn("replyId", list);
					example.createCriteria();
					cmsReplyLikes = cmsReplyLikeService.selectByExample(example);
				}
			}

			List<CmsReplyLike> finalCmsReplyLikes = cmsReplyLikes;
			List<CmsReplyWrap> cmsReplyWraps= pageBean.getList().stream().map(cmsReplyBO -> {
				CmsReplyWrap cmsReplyWrap = dozerBeanMapper.map(cmsReplyBO,CmsReplyWrap.class);
				finalCmsReplyLikes.stream().anyMatch(cmsReplyLike -> {
					if(cmsReplyBO.getId().equals(cmsReplyLike.getReplyId()) && cmsReplyLike.getLikeType()==1){
						cmsReplyWrap.setLikeStatus(cmsReplyLike.getStatus());
					}
					if(cmsReplyBO.getId().equals(cmsReplyLike.getReplyId()) && cmsReplyLike.getLikeType()==2){
						cmsReplyWrap.setDislikeStatus(cmsReplyLike.getStatus());
					}
					return false;
				});
				return cmsReplyWrap ;
			}).collect(Collectors.toList());

			PageBean<CmsReplyWrap> cmsReplyWrapPageBean = new PageBean<>();
			cmsReplyWrapPageBean.setPageCurrent(pageBean.getPageCurrent());
			cmsReplyWrapPageBean.setPageSize(pageBean.getPageSize());
			cmsReplyWrapPageBean.setTotalCount(pageBean.getTotalCount());
			cmsReplyWrapPageBean.setTotalPage(pageBean.getTotalPage());
			cmsReplyWrapPageBean.setList(cmsReplyWraps);
			return new Result(200,"查询成功！",cmsReplyWrapPageBean);
		}catch (Exception e) {
			e.printStackTrace();
			return new Result(400,"查询失败，服务器发生异常，请管理员联系！");
		}
	}


	@ResponseBody
	@RequestMapping(method=RequestMethod.POST,value={"/reply/like"})
	public Result replyLike(HttpServletRequest request, @Validated CmsReplyLikeVO cmsReplyLikeVO, Errors errors, @GetRequestInfo RequestDefaultInfo requestInfo) {

		try {

			if (errors.hasErrors()) {
				return new Result(400,errors.getFieldError().getDefaultMessage());
			}
			Subject subject = SecurityUtils.getSubject();
			if(!subject.isAuthenticated()){
				String message = messageSource.getMessage("user.login",new Object[]{}, request.getLocale());
				logger.error(message);
				return new Result(5001,message);
			}
			Member member = (Member) subject.getPrincipal();
			CmsReplyLike cmsReplyLike = new CmsReplyLike();
			cmsReplyLike.setCreateTime(new Date());
			cmsReplyLike.setMemberId(member.getId());
			cmsReplyLike.setReplyId(cmsReplyLikeVO.getReplyId());
			cmsReplyLike.setLikeType(cmsReplyLikeVO.getLikeType());
			cmsReplyLike.setIp(requestInfo.getRequestIp());
			cmsReplyLike.setStatus(cmsReplyLikeVO.getStatus());
			cmsReplyService.like(cmsReplyLike);
			return new Result(200,"点赞成功！",request.getHeader("Referer"));
		}catch (Exception e) {
			String message = messageSource.getMessage("server.error.500",new Object[]{}, request.getLocale());
			logger.error(message,e);
			return new Result(400,message);
		}
	}


	@ResponseBody
	@RequestMapping(method=RequestMethod.GET,value={"/reply/like"})
	public Result findReplyLike(Long replyId ,HttpServletRequest request) {

		try {

			Subject subject = SecurityUtils.getSubject();
			if(!subject.isAuthenticated()){
				String message = messageSource.getMessage("user.login",new Object[]{}, request.getLocale());
				logger.error(message);
				return new Result(5001,message);
			}
			Member member = (Member) subject.getPrincipal();
			CmsReplyLikeCondition cmsReplyLikeCondition = new CmsReplyLikeCondition();
			cmsReplyLikeCondition.setReplyId(replyId);
			cmsReplyLikeCondition.setMemberId(member.getId());
			cmsReplyLikeCondition.setStatus((short) 1);
			List<CmsReplyLike> cmsReplyLikeList = cmsReplyLikeService.selectCmsReplyLike(cmsReplyLikeCondition);
			return new Result(200,"查询成功！",cmsReplyLikeList);
		}catch (Exception e) {
			e.printStackTrace();
			return new Result(400,"查询失败，服务器发生异常，请管理员联系！");
		}
	}

}
